<!--
author:        hejiyang <silentmanager@163.com>
date:          2024-11-24 11:10:27
component:     index
Copyright © YourCompanyName All rights reserved
已回款
-->
<template>
  <el-card>
    <FormComponent ref="formRef" :config="formConfig">
      <template #submit>
        <div style="margin-left: 24px">
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" />搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" />重置</el-button>
        </div>
      </template>
    </FormComponent>
  </el-card>

  <!-- 表格 -->
  <el-card style="margin-top: 24px">
    <el-table v-loading="loading" :data="list" style="width: 100%">
      <el-table-column label="序号" width="80">
        <template #default="scope">
          {{ scope.$index + 1 + (queryParams.pageNo - 1) * queryParams.pageSize }}
        </template>
      </el-table-column>
      <el-table-column label="订单号" prop="orderNo" />
      <el-table-column label="录入人" prop="creatorName" />
      <el-table-column label="录入班组" prop="teamName" />
      <el-table-column label="客户姓名" prop="customerName" />
      <el-table-column label="客户手机号" prop="customerPhone">
        <template #default="{ row }">
          <span>{{ formatPhoneNumber(row.customerPhone) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" prop="address" />
      <el-table-column label="套餐名称" prop="orderPackageName" />
      <el-table-column label="套餐总金额" prop="totalAmount" />
      <el-table-column label="预付款" prop="packagePrepayment" />
      <el-table-column label="备注" prop="orderNote" />
      <el-table-column label="修改时间" prop="logisticUpdateTime" />
      <el-table-column label="录单时间" prop="createTime" />
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <div style="display: flex">
            <el-button
              link
              type="primary"
              v-hasPermi="['bms:order-info:re-order']"
              @click="handlePlaceOrder(scope.row)"
              >下单</el-button
            >
            <el-button
              v-hasPermi="['bms:order-info:detail']"
              link
              type="primary"
              @click="viewDetails(scope.row)"
              >详情</el-button
            >
            <el-button
              v-hasPermi="['bms:order-note:create']"
              link
              type="primary"
              @click="showRemarkDialog(scope.row)"
              >备注</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </el-card>
  <!-- 备注弹窗 -->
  <OrderRemark :remarkId="remarkId" @success="getList" v-model:visible="isRemarkDialogVisible" />
  <!-- 客户详情抽屉 -->
  <OrderDetail
    :orderDetailId="orderDetailId"
    v-model="isDetailDrawerVisible"
    :detailItem="detailItem"
    @success="getList"
  />
</template>

<script lang="ts" setup>
import { CustomerTypeOptions } from '@/mock'
import OrderRemark from '@/views/order/all/components/orderRemark.vue'
import OrderDetail from '@/views/order/all/components/orderDetail.vue'
import { useDeptList } from '@/hooks/useDeptList'
import { lockStatus, simpleListUser } from '@/api/order/create'
import { defaultProps } from '@/utils/tree'
import FormComponent from '@/components/FormComponent/index.vue'
import { pageLogistics } from '@/api/logistics'
import { pageCustomerUser } from '@/api/customer'
import { defaultTime, formatPhoneNumber } from '@/utils'
const router = useRouter()
// ----------------------------- 下单 -----------------------------
const handlePlaceOrder = async (row) => {
  try {
    const isLock = await lockStatus(row.customerPhone)
    const data = {
      customerPhone: row.customerPhone,
      customerName: row.customerName,
      address: row.address,
      customerType: row.customerType,
      gender: row.gender,
      age: row.age,
      lock: isLock.data
    }
    router.push({
      name: 'Creation',
      state: { data }
    })
  } catch (e) {
    console.error(e)
  }
}
// ----------------------------- 备注弹窗状态 -----------------------------
const remarkId = ref(0)
const isRemarkDialogVisible = ref<boolean>(false)
// 显示弹窗的处理函数
const showRemarkDialog = (row) => {
  remarkId.value = row.id
  isRemarkDialogVisible.value = true
}
// ----------------------------- 详情抽屉状态 -----------------------------
const isDetailDrawerVisible = ref(false)
const orderDetailId = ref(0)
const detailItem = ref<pageCustomerUser>()
const viewDetails = (row) => {
  orderDetailId.value = row.id
  isDetailDrawerVisible.value = true
}
// --------------------  表格  ---------------------
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
// 分页
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await pageLogistics({
      ...queryParams,
      ...formRef.value?.formData,
      logisticStatus: 5,
      auditTime: formRef.value?.formData.auditTime,
      createTime: formRef.value?.formData.createTime
    })
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  formRef.value?.handleReset()
  handleQuery()
}

/** 初始化 */
onMounted(() => {
  getList()
})
// ==================== 表单  ====================
const formRef = ref<InstanceType<typeof FormComponent>>()
const { deptList } = useDeptList()
const userList = ref<{ label: string; value: number }[]>([])
const dUserList = ref<{ label: string; value: number }[]>([])
const simpleListUserFn = async (deptId: string, type: 'department' | 'teamId') => {
  try {
    if (!deptId) {
      return
    }
    const res = await simpleListUser({ deptId })
    const data = res.map((item) => {
      return {
        label: item.nickname,
        value: item.id
      }
    })
    if (type === 'department') {
      dUserList.value = data
    } else {
      userList.value = data
    }
  } catch (e) {
    console.error(e)
  }
}
watch(
  [() => formRef.value?.formData.teamId],
  ([newTeam]) => {
    formRef.value?.setSingleData('creator', '')
    simpleListUserFn(newTeam, 'teamId')
  },
  { deep: true }
)

watch(
  [() => formRef.value?.formData.department],
  ([newDepartment]) => {
    formRef.value?.setSingleData('contactPerson', '')
    simpleListUserFn(newDepartment, 'department')
  },
  { deep: true }
)
const formConfig = ref([
  {
    label: '录入人',
    prop: 'teamId',
    type: 'tree',
    options: {
      placeholder: '请选择录入组织',
      style: 'width: 240px',
      data: deptList,
      props: defaultProps,
      nodeKey: 'id',
      checkStrictly: true
    }
  },
  {
    label: '',
    prop: 'creator',
    type: 'select',
    options: {
      placeholder: '请选择录入人',
      style: 'width: 240px',
      options: userList
    }
  },
  {
    label: '对接人',
    prop: 'department',
    type: 'tree',
    options: {
      placeholder: '请选择对接组织',
      style: 'width: 240px',
      data: deptList,
      props: defaultProps,
      nodeKey: 'id',
      checkStrictly: true
    }
  },
  {
    label: '',
    prop: 'contactPerson',
    type: 'select',
    options: {
      placeholder: '请选择对接人',
      style: 'width: 240px',
      options: dUserList
    }
  },
  {
    label: '客户姓名',
    prop: 'customerName',
    type: 'input',
    options: { placeholder: '请输入客户姓名' }
  },
  {
    label: '客户电话',
    prop: 'customerPhone',
    type: 'input',
    options: { placeholder: '请输入客户电话' }
  },
  {
    label: '客户类型',
    prop: 'customerType',
    type: 'select',
    options: {
      placeholder: '请选择客户类型',
      style: 'width: 240px',
      options: CustomerTypeOptions
    }
  },
  {
    label: '订单号',
    prop: 'orderNo',
    type: 'input',
    options: { placeholder: '请输入订单号' }
  },
  {
    label: '运单号',
    prop: 'logisticNo',
    type: 'input',
    options: { placeholder: '请输入运单号' }
  },
  {
    label: '客户地址',
    prop: 'address',
    type: 'input',
    options: { placeholder: '请输入客户地址' }
  },
  {
    label: '商品名称',
    prop: 'orderPackageName',
    type: 'input',
    options: { placeholder: '请输入商品名称' }
  },
  {
    label: '订单总金额',
    prop: 'totalAmount',
    type: 'number',
    options: {
      placeholder: '请输入订单总金额',
      style: { width: '240px' },
      precision: '2',
      min: '0'
    }
  },
  {
    label: '录入人班组',
    prop: 'username',
    type: 'tree',
    options: {
      placeholder: '请选择录入人班组',
      style: 'width: 240px',
      data: deptList,
      props: defaultProps,
      nodeKey: 'id',
      checkStrictly: true
    }
  },
  {
    label: '审核时间',
    prop: 'auditTime',
    type: 'date',
    options: {
      type: 'datetimerange',
      defaultTime: defaultTime,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      rangeSeparator: '-',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间'
    }
  },
  {
    label: '录入时间',
    prop: 'createTime',
    type: 'date',
    options: {
      type: 'datetimerange',
      defaultTime: defaultTime,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      rangeSeparator: '-',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间'
    }
  }
])
</script>
